#!usr/bin/python
#encoding=utf-8


import urllib
import time
import uuid
from wm.lib import monitorlib
from datetime import datetime
from wm.etc.config import ALARMTYPE
from wm.lib.loglib import log_error
from wm.db.TransactionManager import TransactionManager

def website_html_load_time(host, count = 1):
    for i in xrange(count):
        try:
            start = datetime.now()
            urllib.urlopen(str(host))
            end = datetime.now()
        except Exception as e:
            log_error("website_html_load_time():"+str(e))
            time.sleep(1) 
            continue
        htmlloadtime = (end - start).microseconds /1000000.0
        return True ,{"htmlloadtime":htmlloadtime}
    return False ,{"htmlloadtime":0}

def html_load_time_alarm(row):
    try:
        sql = None
        isalarm,time = website_html_load_time(row[1])
        tran = TransactionManager()
        try:
            if isalarm == False or time['htmlloadtime'] > row[6]:
                alarmcontent = 'html load time:'+str(float('%.3f'%time['htmlloadtime']))
                alarmid = uuid.uuid1().__str__().replace("-","") 
                sql = "insert into alarmevent("+\
                             "id,createDate,modifyDate,alertCategory,alertContent,occurrenceDate,"+\
                            "status,websiteName,websiteConfigInfo_id) "+\
                            "values('" + alarmid + "'," + " CURRENT_TIMESTAMP()," + " CURRENT_TIMESTAMP()," +\
                            str(ALARMTYPE['HTML_LOAD_TIME_ALARM']) + ",'" + alarmcontent + "'," + "CURRENT_TIMESTAMP()," + str(0) + ",'" + row[2] + "'," +\
                            "'" + row[0] + "')"        
                tran.execute(sql)
                monitorlib.update_recent_alarmevent(tran,row[0],row[2],str(ALARMTYPE['HTML_LOAD_TIME_ALARM']),alarmcontent)
                
                sql = "insert into htmlloadtime("+\
                            "id,createDate,modifyDate,loadTime,isNomal,alarmEvent_id,websiteConfigInfo_id) "+\
                            "values(replace(uuid(),'-','')," + "CURRENT_TIMESTAMP(),CURRENT_TIMESTAMP()" +\
                            "," + str(float('%.3f'%time['htmlloadtime'])) + "," + str(1) + ",'"+ str(alarmid) + "','" + row[0] + "')"    
            
            else:
                sql = "insert into htmlloadtime("+\
                                 "id,createDate,modifyDate,loadTime,isNomal,websiteConfigInfo_id) "+\
                                 "values(replace(uuid(),'-','')," + "CURRENT_TIMESTAMP(),CURRENT_TIMESTAMP()" +\
                                 ",'" + str(float('%.3f'%time['htmlloadtime'])) + "'," + str(0) + ",'" + row[0] + "')" 
            print sql
            tran.execute(sql)
            tran.commitTransaction()
        except:
            tran.rollbackTransaction()
        finally:
            tran.close()
    except Exception as e:
        log_error("html_load_time_alarm():"+str(e))
        print "html_load_time_alarm():",str(e)
